#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include "usart.h"
#include "esp8266_driver.h"
#include "app_program.h"


UART_HandleTypeDef *esp_uart;
uint8_t rx_buffer[ESP8266_BUFFER_SIZE];
volatile uint16_t rx_index = 0;
volatile uint8_t rx_flag = 0;

// 接收数据处理（示例）
void ESP8266_ProcessReceivedData(uint8_t *data) {
    if(rx_flag) {
        rx_buffer[rx_index] = '\0';
        // printf("rx_buffer:%s\n", rx_buffer);
        // 串口接收的数据放到队列等待处理
        enqueue(queue, (const char *)rx_buffer);

        rx_index = 0;
        rx_flag = 0;
    }
}


// 初始化ESP8266
void ESP8266_Init(UART_HandleTypeDef *huart) {
    esp_uart = huart;
    char cmd_buf[128];
    // 硬件复位（可选）
    // HAL_GPIO_WritePin(ESP_RST_GPIO_Port, ESP_RST_Pin, GPIO_PIN_RESET);
    // HAL_Delay(100);
    // HAL_GPIO_WritePin(ESP_RST_GPIO_Port, ESP_RST_Pin, GPIO_PIN_SET);
    // HAL_Delay(2000); // 等待模块启动

    // 开启串口接收中断
    HAL_UART_Receive_IT(esp_uart, &rx_buffer[rx_index], 1);
    
    // 发送初始AT指令测试
    while(ESP8266_SendCommand("AT", "OK", 1000) != ESP_OK) {
        HAL_Delay(1000); // 等待模块就绪
    }
    // 基础配置
    ESP8266_SendCommand("AT+CWMODE=1", "OK", 1000); // 设置为station模式
    ESP8266_SendCommand("AT+CIPMUX=1", "OK", 1000); // 启动多连接
    
    //  连接WiFi
    sprintf(cmd_buf, "AT+CWJAP=\"%s\",\"%s\"", WIFI_SSID, WIFI_PASS);
    ESP8266_SendCommand(cmd_buf, "OK", 10000);
    
    // 连接WiFi
    ESP8266_SendCommand("AT+CIPSERVER=1,8080", "OK", 1000); //开启TCP服务端连接
    
    ESP8266_SendCommand("AT+CIPDINFO=1", "OK", 1000);       // 启用连接详细信息
    
    ESP8266_SendCommand("AT+CIFSR", "OK", 1000);            // 显示自己的ip地址

    // ESP8266_SendCommand("AT+CIPSRIP=1", "OK", 1000);    // 显示远程IP

}

// 发送AT指令并等待响应
ESP_Status ESP8266_SendCommand(const char *cmd, const char *expect, uint32_t timeout) {
    char full_cmd[256];
    snprintf(full_cmd, sizeof(full_cmd), "%s\r\n", cmd);
    
    rx_index = 0;
    rx_flag = 0;
    
    // 发送命令
    if(HAL_UART_Transmit(esp_uart, (uint8_t*)full_cmd, strlen(full_cmd), timeout) != HAL_OK) {
        return ESP_ERROR;
    }
    
    // 等待响应
    uint32_t start = HAL_GetTick();
    while((HAL_GetTick() - start) < timeout) {
        if(rx_flag) {
            rx_buffer[rx_index] = '\0'; // 添加字符串结束符
            
            if(strstr((char*)rx_buffer, expect) != NULL) {
                return ESP_OK;
            } else if(strstr((char*)rx_buffer, "ERROR") != NULL) {
                return ESP_ERROR;
            }
            
            rx_flag = 0;
        }
    }
    return ESP_TIMEOUT;
}

// 发送原始数据
ESP_Status ESP8266_SendData(const uint8_t *data, uint16_t len) {
    if(HAL_UART_Transmit(esp_uart, data, len, ESP8266_TIMEOUT) != HAL_OK) {
        return ESP_ERROR;
    }
    return ESP_OK;
}

// 串口接收中断回调
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if(huart == esp_uart) {
        if(rx_index < ESP8266_BUFFER_SIZE - 1) {
            rx_index++;
            // 检测到换行符认为收到完整响应
            if((rx_buffer[rx_index-1] == '\n') && (rx_buffer[rx_index-2] == '\r') ) {
                rx_flag = 1;
            }
        } else {
            rx_index = 0; // 防止缓冲区溢出
        }
        HAL_UART_Receive_IT(esp_uart, &rx_buffer[rx_index], 1);
    }
}

// 发送数据测试使用
void send_encrypted_data(const char * paystr) {
    
    int ret;
    // 原始payload数据（base64编码）
    const char* payload = paystr;
    
    // 动态构建JSON（避免缓冲区溢出）
    char json_data[256];
    snprintf(json_data, sizeof(json_data), 
        "{\\\"payload\\\":\\\"%s\\\"\\,\\\"mode\\\":1}", // 注意双反斜杠转义
        payload);

    // 构建完整AT指令
    char at_cmd[350];
    snprintf(at_cmd, sizeof(at_cmd),
        "AT+HTTPCLIENT=3,1,\"http://%s:%d/api/upload\",\"\",\"\",1,\"%s\"",
        IP_ADDR, PORT, json_data);

    // 验证指令长度（ESP8266 AT限制通常为256字节）
    if (strlen(at_cmd) > 255) {
        printf("[错误] 指令长度 %d 超过限制\n", strlen(at_cmd));
        return;
    }
    printf("%s\n", at_cmd);
    ret = ESP8266_SendCommand(at_cmd, "OK", 10000);
    printf("ret = %d\n", ret);

    // 发送指令
    if (ret) {
        printf("[错误] 发送失败\n");
    }

    // ESP_Status ret1 = ESP8266_SendCommand("AT+CWLIF", "OK", ESP8266_TIMEOUT);
    // printf("ret = %d\n", ret1);
}

// AT+HTTPCLIENT=2,0,"http://192.168.83.134:3000/api/status","","",1
// AT+HTTPCLIENT=3,1,"http://192.168.83.134:3000/api/upload","","",1,"{\"payload\":\"BSDoFF3V7jW8pOBkai3YomLpPrNdqKj/s4Hmbz2VORhe+GDJbr1lCykVC8CTSExTGlh8Dm3/hOuwRX0ZIS8rqzXnc8YAbS2OxwOT5MCt1M9nlBfhcf9vonISnKqELfCqkxgMDDO2wENw6+VcOtuIoQ==\",\"mode\":\"cbc\"}"

// AT+HTTPCLIENT=3,1,"http://192.168.83.134:3000/api/test","","",1,"{\"any_key\":\"any_value\"}"
// AT+HTTPCLIENT=3,1,"http://192.168.83.134:3000/api/upload","","",1,"{\"payload\":\"BSDoFF3V7jW8pOBkai3YomLpPrNdqKj/s4Hmbz2VORhe+GDJbr1lCykVC8CTSExTGlh8Dm3/hOuwRX0ZIS8rqzXnc8YAbS2OxwOT5MCt1M9nlBfhcf9vonISnKqELfCqkxgMDDO2wENw6+VcOtuIoQ==\"\,\"mode\":1}"

